<template>
  <div class="system-settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="card">
        <!-- 短信设置 -->
        <el-tab-pane label="短信配置" name="sms">
          <el-form
            ref="smsFormRef"
            :model="smsForm"
            :rules="smsRules"
            label-width="180px"
            label-position="right"
          >
            <el-form-item label="短信服务商" prop="sms_provider">
              <el-select
                v-model="smsForm.sms_provider"
                placeholder="请选择短信服务商"
                style="width: 100%"
              >
                <el-option
                  v-for="item in smsProviders"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="Access Key ID" prop="access_key_id">
              <el-input
                v-model="smsForm.access_key_id"
                placeholder="请输入Access Key ID"
                show-password
              />
            </el-form-item>

            <el-form-item label="Access Key Secret" prop="access_key_secret">
              <el-input
                v-model="smsForm.access_key_secret"
                placeholder="请输入Access Key Secret"
                show-password
              />
            </el-form-item>

            <el-form-item label="短信签名" prop="sms_signature">
              <el-input
                v-model="smsForm.sms_signature"
                placeholder="请输入短信签名"
              />
            </el-form-item>

            <el-form-item label="默认模板ID" prop="default_template_id">
              <el-input
                v-model="smsForm.default_template_id"
                placeholder="请输入默认模板ID"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitSmsForm">保存</el-button>
              <el-button @click="resetSmsForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 客服设置 -->
        <el-tab-pane label="客服信息" name="customerService">
          <el-form
            ref="serviceFormRef"
            :model="serviceForm"
            :rules="serviceRules"
            label-width="180px"
            label-position="right"
          >
            <el-form-item label="客服电话" prop="phone">
              <el-input
                v-model="serviceForm.phone"
                placeholder="请输入客服电话"
              />
            </el-form-item>

            <el-form-item label="客服邮箱" prop="email">
              <el-input
                v-model="serviceForm.email"
                placeholder="请输入客服邮箱"
              />
            </el-form-item>

            <el-form-item label="客服工作时间" prop="workTime">
              <el-input
                v-model="serviceForm.workTime"
                placeholder="例如: 周一至周五 9:00-18:00"
              />
            </el-form-item>

            <el-form-item label="客服二维码">
				<Uploadimg :limit="1" v-model="serviceForm.qrCode" :value="serviceForm.qrCode" @upload="onUpload" msg="上传客服二维码图片"/>

              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :limit="1"
                :on-change="handleQrCodeChange"
                :on-remove="handleQrCodeRemove"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="el-upload__tip">
                上传客服二维码图片，建议尺寸 300x300px
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitServiceForm"
                >保存</el-button
              >
              <el-button @click="resetServiceForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 应用版本 -->
        <el-tab-pane label="应用版本" name="version" v-if="0">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="当前版本">
              {{ versionInfo.currentVersion }}
            </el-descriptions-item>
            <el-descriptions-item label="最新版本">
              <span :class="{ 'new-version': hasNewVersion }">
                {{ versionInfo.latestVersion }}
                <el-tag v-if="hasNewVersion" size="small" type="success"
                  >新版本</el-tag
                >
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="更新日期">
              {{ versionInfo.updateTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新内容">
              <div class="update-content">
                <div
                  v-for="(item, index) in versionInfo.updateContent"
                  :key="index"
                  class="update-item"
                >
                  <span class="update-type" :class="getUpdateTypeClass(item.type)">{{ item.type }}:</span>
                  <span>{{ item.content }}</span>
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <div class="version-actions">
            <el-button
              type="primary"
              :loading="checkingUpdate"
              @click="checkForUpdates"
            >
              检查更新
            </el-button>
          
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed,onMounted,defineAsyncComponent} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
const Uploadimg = defineAsyncComponent(() => import('/@/components/Upload/singleImage.vue'));

import {
    updateCustomerService,
    addCustomerService,
    getCustomerServiceList,
    updateSmsConfig,
    addSmsConfig,
    getSmsConfig
} from '/@/api/SmsConfig/index'

const apiUrl = ref('');

const onUpload = (data:any) => {
    console.log('dda',data)
    serviceForm.qrCode = data
}

onMounted(() => {
    getConfig()
    getCustomer()
})
const getCustomer = async () => {
    const res = await getCustomerServiceList()
    serviceForm.email = res.data.email
    serviceForm.phone = res.data.phone
    serviceForm.qrCode = res.data.qrCode
    serviceForm.workTime = res.data.workTime
    serviceForm.id = res.data.id
}
const getConfig = async () => {
    const res = await getSmsConfig()
    smsForm.access_key_id = res.data.access_key_id
    smsForm.access_key_secret = res.data.access_key_secret
    smsForm.default_template_id = res.data.default_template_id
    smsForm.sms_provider = res.data.sms_provider
    smsForm.sms_signature = res.data.sms_signature
    smsForm.id = res.data.id
}

// 短信配置
interface SmsForm {
  sms_provider: string
  access_key_id: string
  access_key_secret: string
  sms_signature: string
  default_template_id: string
  id:''
}

// 客服信息
interface ServiceForm {
  phone: string
  email: string
  workTime: string
  qrCode: string
  id:''
}

// 版本信息
interface VersionInfo {
  currentVersion: string
  latestVersion: string
  updateTime: string
  updateContent: {
    type: string
    content: string
  }[]
}

// 激活的标签页
const activeTab = ref('sms')

// 短信服务商选项
const smsProviders = [
  { label: '阿里云短信', value: 'aliyun' },
  { label: '腾讯云短信', value: 'tencent' },
  { label: '云片短信', value: 'yunpian' },
  { label: '其他', value: 'other' }
]

// 短信表单
const smsForm = reactive<SmsForm>({
  sms_provider: '',
  access_key_id: '',
  access_key_secret: '',
  default_template_id: '',
  sms_signature: '',
  id:1
})

// 短信表单验证规则
const smsRules = reactive<FormRules<SmsForm>>({
  sms_provider: [{ required: true, message: '请选择短信服务商', trigger: 'change' }],
  access_key_id: [
    { required: true, message: '请输入Access Key ID', trigger: 'blur' }
  ],
  access_key_secret: [
    { required: true, message: '请输入Access Key Secret', trigger: 'blur' }
  ],
  sms_signature: [{ required: true, message: '请输入短信签名', trigger: 'blur' }]
})

// 客服表单
const serviceForm = reactive<ServiceForm>({
  phone: '',
  email: '',
  workTime: '周一至周五 9:00-18:00',
  qrCode: '',
  id:1
})

// 客服表单验证规则
const serviceRules = reactive<FormRules<ServiceForm>>({
  phone: [
    { required: true, message: '请输入客服电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
      message: '请输入正确的电话号码',
      trigger: 'blur'
    }
  ],
  email: [
    { required: false, message: '请输入客服邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ]
})

// 版本信息
const versionInfo = reactive<VersionInfo>({
  currentVersion: '1.0.0',
  latestVersion: '1.0.1',
  updateTime: '2025-08-15',
  updateContent: [
    { type: '新增', content: '新增用户反馈功能' },
    { type: '优化', content: '优化系统性能，提升响应速度' },
    { type: '修复', content: '修复已知的若干问题' }
  ]
})

// 检查更新状态
const checkingUpdate = ref(false)

// 是否有新版本
const hasNewVersion = computed(() => {
  return versionInfo.currentVersion !== versionInfo.latestVersion
})

// 表单引用
const smsFormRef = ref<FormInstance>()
const serviceFormRef = ref<FormInstance>()

// 提交短信表单
const submitSmsForm = () => {
  smsFormRef.value?.validate((valid) => {
    if (valid) {
      console.log('ssss',smsForm)
      addSms(smsForm)
      // 这里调用API保存配置
      
    } else {
      ElMessage.error('请填写完整的短信配置信息')
      return false
    }
  })
}

const addSms = async (param:Object) => {
    const res = await addSmsConfig(param)
    console.log('ssssaaaa',res)
    if(res.code === 200) {
        getConfig()
        ElMessage.success('短信配置保存成功')
    }
}

// 重置短信表单
const resetSmsForm = () => {
  smsFormRef.value?.resetFields()
}

// 提交客服表单
const submitServiceForm = () => {
  serviceFormRef.value?.validate((valid) => {
    if (valid) {
     addCustomer(serviceForm)
      // 这里调用API保存配置
    } else {
      ElMessage.error('请填写完整的客服信息')
      return false
    }
  })
}

const addCustomer =  async (param:Object) => {
    const res = await addCustomerService(param)
    if(res.code === 200) {
        getCustomer()
        ElMessage.success('客服信息保存成功')
    }
}

// 重置客服表单
const resetServiceForm = () => {
  serviceFormRef.value?.resetFields()
}

// 处理二维码上传
const handleQrCodeChange: UploadProps['onChange'] = (file) => {
  // 这里可以添加上传逻辑
  serviceForm.qrCode = URL.createObjectURL(file.raw!)
}

// 处理二维码移除
const handleQrCodeRemove = () => {
  serviceForm.qrCode = ''
}

// 检查更新
const checkForUpdates = () => {
  checkingUpdate.value = true
  // 模拟API调用
  setTimeout(() => {
    checkingUpdate.value = false
    if (hasNewVersion.value) {
      ElMessage.success(`发现新版本 ${versionInfo.latestVersion}`)
    } else {
      ElMessage.info('当前已是最新版本')
    }
  }, 1500)
}



// 获取更新类型样式
const getUpdateTypeClass = (type: string) => {
  switch (type) {
    case '新增':
      return 'type-new'
    case '优化':
      return 'type-optimize'
    case '修复':
      return 'type-fix'
    default:
      return ''
  }
}
</script>

<style lang="scss" scoped>
.system-settings-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);

  .settings-card {
    max-width: 1200px;
    margin: 0 auto;
    min-height: 85vh;
  }

  .card-header {
    font-size: 18px;
    font-weight: bold;
  }

  .new-version {
    color: #67c23a;
    margin-right: 10px;
  }

  .update-content {
    .update-item {
      margin-bottom: 8px;
      line-height: 1.5;

      .update-type {
        display: inline-block;
        width: 50px;
        margin-right: 10px;
        text-align: right;

        &.type-new {
          color: #67c23a;
        }

        &.type-optimize {
          color: #e6a23c;
        }

        &.type-fix {
          color: #f56c6c;
        }
      }
    }
  }

  .version-actions {
    margin-top: 20px;
    text-align: center;
  }
}
</style>